package cn.z2huo.demo.spring.transactional.service.programmatic;

import cn.z2huo.core.util.IdUtils;
import cn.z2huo.demo.mapper.user.UserMapper;
import cn.z2huo.demo.model.dataobject.user.UserDO;
import cn.z2huo.demo.spring.transactional.config.MyTransactionManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;

@Slf4j
@Service
public class TransactionManagerServiceImpl {

    @Autowired
    private UserMapper userMapper;

    public void insertUser() {

        TransactionStatus status = MyTransactionManager.start();

        UserDO userDO = new UserDO()
                .setId(IdUtils.nextId())
                .setUserCode("18182222")
                .setUserName("tx-template user " + RandomStringUtils.randomAlphabetic(4));
        userMapper.insertSelective(userDO);
        log.info("insertUser end");

        MyTransactionManager.commit(status);

        log.info("tx end");
    }

    public String insertUserHaveReturn() {

        TransactionStatus status = MyTransactionManager.start();

        UserDO userDO = new UserDO()
                .setId(IdUtils.nextId())
                .setUserCode("18182222")
                .setUserName("tx-template user " + RandomStringUtils.randomAlphabetic(4));
        int result = userMapper.insertSelective(userDO);
        log.info("insertUser end");

        MyTransactionManager.commit(status);

        return Integer.valueOf(1).equals(result) ? "success" : "fail";
    }

    public int insertUserNoTx() {
        UserDO userDO = new UserDO()
                .setId(IdUtils.nextId())
                .setUserCode("18182222")
                .setUserName("no tx user " + RandomStringUtils.randomAlphabetic(4));
        int result = userMapper.insertSelective(userDO);
        return result;
    }

}
